package com.example.testproject.activity;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.testproject.R;
import com.example.testproject.bean.TestBean;
import com.github.barteksc.pdfviewer.PDFView;
import com.jakewharton.rxbinding2.view.RxView;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HttpsURLConnection;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import kotlin.Unit;

/**
 * @Package: com.example.testproject.activity
 * @ClassName: RxJavaActivity
 * @Author: szj
 * @CreateDate: 8/19/21 5:07 PM
 * TODO RxJava
 */
public class RxJavaActivity extends AppCompatActivity {

    //    private final String PATH = "https://steamuserimages-a.akamaihd.net/ugc/931563623911695840/6D1C84C7FAAA6172FC16DF89A0DF824C6198DDE6/?imw=1024&imh=652&ima=fit&impolicy=Letterbox&imcolor=%23000000&letterbox=true";
    private final String PATH = "https://www.gjtool.cn/pdfh5/git.pdf";
    private ProgressDialog progressDialog;
    private TextView tv;

    private final ArrayList<TestBean> testBeanList = new ArrayList<>();
    private PDFView pdfView;

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rx_java);

        Button bt = findViewById(R.id.bt);
        tv = findViewById(R.id.tv);
        pdfView = findViewById(R.id.pdfView);

        //防抖动点击测试
        RxView.clicks(bt).throttleFirst(1, TimeUnit.SECONDS)
                .map(o -> "123")
                .subscribe(unit -> bt.setText(unit));

        for (int i = 0; i < 30; i++) {
            testBeanList.add(new TestBean("王宝强" + i, i * 20, i * 20 % 3 == 0));
        }

        new RetrivePDFfromUrl().execute(PATH);
    }

    // create an async task class for loading pdf file from URL.
    class  RetrivePDFfromUrl extends AsyncTask<String, Void, InputStream> {
        @Override
        protected InputStream doInBackground(String... strings) {
            // we are using inputstream
            // for getting out PDF.
            InputStream inputStream = null;
            try {
                URL url = new URL(strings[0]);
                // below is the step where we are
                // creating our connection.
                HttpURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
                if (urlConnection.getResponseCode() == 200) {
                    // response is success.
                    // we are getting input stream from url
                    // and storing it in our variable.
                    inputStream = new BufferedInputStream(urlConnection.getInputStream());
                }

            } catch (IOException e) {
                // this is the method
                // to handle errors.
                e.printStackTrace();
                return null;
            }
            return inputStream;
        }

        @Override
        protected void onPostExecute(InputStream inputStream) {
            // after the execution of our async
            // task we are loading our pdf in our pdf view.
            Log.i("szj加载了数据",inputStream.toString());
            Toast.makeText(RxJavaActivity.this, "加载了。。AsyncTask", Toast.LENGTH_SHORT).show();
            pdfView.fromStream(inputStream).load();
        }
    }

    @SuppressLint("CheckResult")
    public void onFlatMapClick(View view) {
        Observable
                .just(testBeanList)

//                .create(new ObservableOnSubscribe<ArrayList<TestBean>>() {
//            @Override
//            public void subscribe(ObservableEmitter<ArrayList<TestBean>> e) throws Exception {
//                e.onNext(testBeanList);
//            }
//        })
                //给下面切换子线程
                .observeOn(Schedulers.io())
                .flatMap((Function<ArrayList<TestBean>, ObservableSource<TestBean>>) testBeans -> Observable.fromIterable(testBeans))
                .map(testBean -> testBean.getName())
                //给下面切换主现场
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(testBean -> {
                    Log.i("szjAccept", testBean.toString());
                    tv.append(testBean.toString() + "\n");
                });
    }


    public void onLoadImageClick(View view) {
        ImageView image = findViewById(R.id.image);
        Observable.just(PATH)
                .map(s -> {
                    Log.i("szjBitmap", s);
                    URL url = new URL(s);
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                    //设置连接超时时间
                    urlConnection.setConnectTimeout(5000);

                    if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        //请求服务器
                        return urlConnection.getInputStream();
                    }
                    return null;

                })
                //给上面分配异步线程
                .subscribeOn(Schedulers.io())

                //给下面分配主线程
                .observeOn(AndroidSchedulers.mainThread())

                //订阅 【观察者】
                .subscribe(new Observer<InputStream>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        //订阅开始
                        progressDialog = new ProgressDialog(RxJavaActivity.this);
                        progressDialog.setTitle("pdf加载中");
                        progressDialog.show();
                    }

                    @Override
                    public void onNext(InputStream stream) {
                        if (stream != null) {
                            Log.i("szj加载成功",stream.toString());
                            progressDialog.setTitle("加载成功"+stream);
                            //成功
                            pdfView.fromStream(stream).enableSwipe(true) // allows to block changing pages using swipe
                                    .swipeHorizontal(false)
                                    .enableDoubletap(true)
                                    .defaultPage(0)
//                                    .onLoad(nbPages -> showLoading(false))
// allows to draw something on the current page, usually visible in the middle of the screen
                                    .enableAnnotationRendering(false) // render annotations (such as comments, colors or forms)
                                    .password(null)
                                    .scrollHandle(null)
                                    .enableAntialiasing(true) // improve rendering a little bit on low-res screens
// spacing between pages in dp. To define spacing color, set view background
                                    .spacing(15)
                                    .pages(0, 2, 1, 3, 3, 3) // 选择显示那些page
                                    .enableSwipe(true) // 是否允许滑动切换page
                                    .swipeHorizontal(false)//水平滑动
                                    .enableDoubletap(true)//双击放大
                                    .defaultPage(0)//默认显示page
// allows to draw something on the current page, usually visible in the middle of the screen
//                                    .onDraw(onDrawListener)//可以在onDraw中绘制自定义图形到当前页
// allows to draw something on all pages, separately for every page. Called only for visible pages
//                                    .onDrawAll(onDrawListener)//绘制自定义图形到所有页面
//                                    .onLoad(onLoadCompleteListener) // 在加载完成后调用,调用后开始onRender
//                                    .onPageChange(onPageChangeListener)//page切换监听
//                                    .onPageScroll(onPageScrollListener)//page滚动监听
//                                    .onError(onErrorListener)//错误时回调
//                                    .onPageError(onPageErrorListener)//page加载错误
//                                    .onRender(onRenderListener) // called after document is rendered for the first time 首次渲染后回调
// called on single tap, return true if handled, false to toggle scroll handle visibility
//                                    .onTap(onTapListener)//单击监听
                                    .enableAnnotationRendering(false) // render annotations (such as comments, colors or forms) 是否渲染注解:评论/颜色/forms
                                    .password(null)
                                    .scrollHandle(null)
                                    .enableAntialiasing(true) // improve rendering a little bit on low-res screens
// spacing between pages in dp. To define spacing color, set view background
                                    .spacing(0) //page间隔
//                                    .linkHandler(DefaultLinkHandler) //pdf中链接处理
//                                    .pageFitPolicy(FitPolicy.WIDTH) //page适应策略,宽度优先还是高度优先 3.0.0才有
                                    .load();//加载pdf
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //错误
                        progressDialog.setTitle("失败了" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //订阅结束
//                        if (progressDialog != null && progressDialog.isShowing())
//                            progressDialog.hide();
                    }
                });
    }
}
